import 'package:bluetooth_helper/models/MyHomePageData.dart';
import 'package:bluetooth_helper/utils/MessageHelper.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';

class BluetoothPage extends StatefulWidget {
  BluetoothPage(this._MyHomePageData, this.setStateEvent);

  MyHomePageData _MyHomePageData;
  Function(Function) setStateEvent;

  @override
  State<BluetoothPage> createState() =>
      _BluetoothPageState(_MyHomePageData, this.setStateEvent);
}

class _BluetoothPageState extends State<BluetoothPage> {
  _BluetoothPageState(this._MyHomePageData, this.setStateEvent);

  MyHomePageData _MyHomePageData;
  Function(Function) setStateEvent;

  ///蓝牙打开状态
  var bluetoothIsOpen = true;

  void showMsg(String msg, [bool isShow = true]) {
    debugPrint("[BluetoothPage]:${msg}");
    if (isShow) {
      SmartDialog.showToast(msg);
    }
  }

  void addItem2(ScanResult result) {
    setStateEvent(() => _MyHomePageData.bluetoothList.add(result));
  }

  void clearItem2() {
    setStateEvent(() => _MyHomePageData.bluetoothList.clear());
  }

  void sancfBluetooth() async {
    clearItem2();
    await FlutterBluePlus.stopScan();
    if (await FlutterBluePlus.isSupported == true) {
      showMsg("蓝牙打开成功！");
      this.bluetoothIsOpen = true;
    } else {
      //
      bluetoothIsOpen = false;

      SmartDialog.showNotify(msg: "蓝牙打开失败！", notifyType: NotifyType.error);
      return;
    }

    showMsg("开始监听蓝牙!");
    //订阅监听事件
    var subscription = FlutterBluePlus.onScanResults.listen(
      (results) {
        if (results.isNotEmpty) {
          ScanResult r = results.last; // the most recently found device
          if (r.device.platformName != "") {
            if (!_MyHomePageData.bluetoothList.contains(r)) {
              showMsg("添加蓝牙设备!!!\r\n ${r.device.platformName}");
              addItem2(r);
            }
            showMsg("找到蓝牙设备", false);

            showMsg(
                '${r.device.remoteId}: "${r.advertisementData.advName}" found!',
                false);

            showMsg(r.toString(), false);
          }
        }
      },
      onError: (e) => showMsg(e),
    );
    // showMsg("断开蓝牙连接");
// cleanup: cancel subscription when scanning stops
    FlutterBluePlus.cancelWhenScanComplete(subscription);

// Wait for Bluetooth enabled & permission granted
// In your real app you should use `FlutterBluePlus.adapterState.listen` to handle all states

    await FlutterBluePlus.adapterState
        .where((val) => val == BluetoothAdapterState.on)
        .first;
// Start scanning w/ timeout
// Optional: use `stopScan()` as an alternative to timeout
    await FlutterBluePlus.startScan(timeout: Duration(seconds: 600));
    SmartDialog.showNotify(msg: "蓝牙扫码将持续600s", notifyType: NotifyType.alert);
// wait for scanning to stop
    await FlutterBluePlus.isScanning.where((val) => val == false).first;
  }

  void connectBluetooth(BuildContext context, ScanResult result) async {
    if(await MessageHelper.Confrim(context, "蓝牙连接", "确定连接${result.device.platformName}设备吗")){
      var device = result.device;
      SmartDialog.showLoading(msg: "正在连接[${result.device.platformName}]",clickMaskDismiss: true);
      var isConnect = false;
      var subscription =
      device.connectionState.listen((BluetoothConnectionState state) async {
        if (state == BluetoothConnectionState.disconnected) {
          // 1. typically, start a periodic timer that tries to
          //    reconnect, or just call connect() again right now
          // 2. you must always re-discover services after disconnection!
          // SmartDialog.showNotify(
          //     msg:
          //     "蓝牙连接失败 \r\n ${device.disconnectReason?.code} \r\n ${device..disconnectReason?.description}",
          //     notifyType: NotifyType.error);
        } else {
          SmartDialog.dismiss();
          var isConnect = true;

          SmartDialog.showNotify(
              msg: "蓝牙[${device.platformName}]\r\n连接成功！",
              notifyType: NotifyType.success);
        }
      });

// cleanup: cancel subscription when disconnected
//   - [delayed] This option is only meant for `connectionState` subscriptions.
//     When `true`, we cancel after a small delay. This ensures the `connectionState`
//     listener receives the `disconnected` event.
//   - [next] if true, the the stream will be canceled only on the *next* disconnection,
//     not the current disconnection. This is useful if you setup your subscriptions
//     before you connect.
      device.cancelWhenDisconnected(subscription, delayed: true, next: true);

// Connect to the device
      await device.connect();


// cancel to prevent duplicate listeners
      subscription.cancel();
    }

  }

  @override
  Widget build(BuildContext context) {
    FlutterBluePlus.setLogLevel(LogLevel.verbose, color: false);
    // TODO: implement build
    return Column(
      children: [
        Expanded(
          child: ListView.builder(
              itemCount: _MyHomePageData.bluetoothList.length,
              itemBuilder: (BuildContext context, int index) {
                return ListTile(
                  title: Text(
                      _MyHomePageData.bluetoothList[index].device.platformName),
                  subtitle: Text(_MyHomePageData
                      .bluetoothList[index].device.remoteId
                      .toString()),
                  trailing: ElevatedButton(
                    onPressed: () {
                      connectBluetooth(context,_MyHomePageData.bluetoothList[index]);
                    },
                    child: Icon(Icons.play_arrow),
                  ),
                );
              }),
        ),
        Center(
          child: ElevatedButton(
              onPressed: sancfBluetooth, child: const Text("刷新蓝牙列表")),
        ),
        Divider()
      ],
    );
  }
}
